package com.creditcmsplt.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.creditcmsplt.properties.CollectInfoProperties;

/**
 * baidu api 工具类，包含身份证识别，通用版ocr文字识别两个
 * @author leiyangjun
 *
 */
public enum BaiduApiUtil {
	
	INSTANCE;

//	public static final String APP_ID = "baidu.api.app_id";
//    public static final String API_KEY = "baidu.api.api_key";
//    public static final String SECRET_KEY = "baidu.api.secret_key";
//    
//    public static final String COUNTAPI="baidu.api.countApi";
    
    private static Logger log = LoggerFactory.getLogger(BaiduApiUtil.class);
    
    /**
     * 用于项目中,获取Baidu sdkaipocr对象
     * @param env:属性配置文件参数
     * @return ApiOcr
     */
    private AipOcr getApiOcr(CollectInfoProperties env) {
    	AipOcr client = new AipOcr(env.getBaidu_appid(), env.getBaidu_apikey(), env.getBaidu_secretkey());
        client.setConnectionTimeoutInMillis(60000);
        client.setSocketTimeoutInMillis(60000);
    	return client;
    }
    
    /**
     * 用于test main方法获取apiocr
     * @param app_id:Baidu api_id
     * @param api_key:Baidu api_key
     * @param secret_key:Baidu seccret_key
     * @return ApiOcr
     */
    private AipOcr getApiOcr(String app_id,String api_key,String secret_key) {
    	AipOcr client = new AipOcr(app_id, api_key, secret_key);
        client.setConnectionTimeoutInMillis(60000);
        client.setSocketTimeoutInMillis(60000);
    	return client;
    }
    
    /**
     * 统计Baidu 调用api次数,如果传入token为空或者null时不统计
     * @param cyrzToken:php端token
     * @param evn:配置文件对象
     */
    private void countBaiduApi(String cyrzToken,CollectInfoProperties env) {
    	if(!TextUtils.isEmpty(cyrzToken)||env==null) {
    		Map<String, Object> formparam = new HashMap<String, Object>();
			formparam.put("token", cyrzToken);
			formparam.put("type", 2);
			formparam.put("os", 3);
			HttpUtil.execuateHttpFile(env.getCountApi(), "post",formparam, null);
    	}
    }
    
    /**
     * 统计Baidu 调用api次数,如果传入token为空或者null时不统计
     * @param cyrzToken:token
     * @param countApiUrl:统计api
     */
    private void countBaiduApi(String cyrzToken,String countApiUrl) {
    	if(!TextUtils.isEmpty(cyrzToken)&&!TextUtils.isEmpty(countApiUrl)) {
    		Map<String, Object> formparam = new HashMap<String, Object>();
			formparam.put("token", cyrzToken);
			formparam.put("type", 2);
			formparam.put("os", 3);
			HttpUtil.execuateHttpFile(countApiUrl, "post",formparam, null);
    	}
    }
    
    /**
     * 身份证识别,可以用于main方法测试,测试时不要传入cyrzToken参数
     * @param env :springboot获取属性配置文件对象
     * @param imagePath:要ocr的身份证照片
     * @param isFront:是否身份证正面照,true正面,false反面
     * @param cyrzToken:统计接口的token
     * @return org.json.JSONObject
     */
	public JSONObject idcardRecognition(String app_id,String api_key,String secret_key,String imagePath,boolean isFront,String cyrzToken,String countApiUrl) {
		try {
			AipOcr aipOcr=getApiOcr(app_id, api_key, secret_key);
			org.json.JSONObject jsonObject=aipOcr.idcard(imagePath,isFront, new HashMap<String, String>());
			countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
    
    /**
     * 身份证识别
     * @param env :springboot获取属性配置文件对象
     * @param imagePath:要ocr的身份证照片
     * @param isFront:是否身份证正面照
     * @param cyrzToken:统计接口的token
     * @return org.json.JSONObject
     */
	public JSONObject idcardRecognition(CollectInfoProperties env,String imagePath,boolean isFront,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.idcard(imagePath,isFront, new HashMap<String, String>());
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	 /**
     * 身份识别
     * @param env :springboot获取属性配置文件对象
     * @param bytes:要ocr的身份证照片二进制
     * @param isFront:是否身份证正面照
     * @param cyrzToken:统计接口的token
     * @return org.json.JSONObject
     */
	public JSONObject idcardRecognition(CollectInfoProperties env,byte[] bytes,boolean isFront,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.idcard(bytes,isFront, new HashMap<String, String>());
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 通用文字识别
	 * @param env :springboot获取属性配置文件对象
	 * @param imagePath:要ocr的身份证照片
	 * @param cyrzToken:统计接口的token
	 * @return org.json.JSONObject
	 */
	public JSONObject generalRecognition(CollectInfoProperties env,String imagePath,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.basicGeneral(imagePath, new HashMap<String, String>());
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 通用文字识别
	 * @param env :springboot获取属性配置文件对象
	 * @param imagePath:要ocr的身份证照片
	 * @param cyrzToken:统计接口的token
	 * @return org.json.JSONObject
	 */
	public JSONObject generalRecognition(CollectInfoProperties env,byte[] bytes,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.basicGeneral(bytes, new HashMap<String, String>());
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 通用文字识别
	 * @param env :springboot获取属性配置文件对象
	 * @param imagePath:要ocr的身份证照片
	 * @param cyrzToken:统计接口的token
	 * @return org.json.JSONObject
	 */
	public JSONObject generalRecognition(String app_id,String api_key,String secret_key,String imagePath,String cyrzToken,String countApiUrl) {
		try {
			AipOcr aipOcr=getApiOcr(app_id, api_key, secret_key);
			org.json.JSONObject jsonObject=aipOcr.basicGeneral(imagePath, new HashMap<String, String>());
			countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 表格识别
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public String tableRecognitionAsync(CollectInfoProperties env,byte[] bytes,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.tableRecognitionAsync(bytes);
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			JSONArray jsonArray=resultJson.getJSONArray("result")==null?null:resultJson.getJSONArray("result");
			String request_id=jsonArray==null||jsonArray.size()<=0?"":((JSONObject)jsonArray.get(0)).getString("request_id");
			return request_id;
		} catch (Exception e) {
			log.error("",e);
		}
		return "";
	}
	
	/**
	 * 表格识别
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public String tableRecognitionAsync(CollectInfoProperties env,String imageFile,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.tableRecognitionAsync(imageFile);
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			JSONArray jsonArray=resultJson.getJSONArray("result")==null?null:resultJson.getJSONArray("result");
			String request_id=jsonArray==null||jsonArray.size()<=0?"":((JSONObject)jsonArray.get(0)).getString("request_id");
			return request_id;
		} catch (Exception e) {
			log.error("",e);
		}
		return "";
	}
	
	/**
	 * 表格识别
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public String tableRecognitionAsync(String app_id,String api_key,String secret_key,String imageFile,String cyrzToken,String countApiUrl) {
		try {
			AipOcr aipOcr=getApiOcr(app_id,api_key,secret_key);
			org.json.JSONObject jsonObject=aipOcr.tableRecognitionAsync(imageFile);
			countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			JSONArray jsonArray=resultJson.getJSONArray("result")==null?null:resultJson.getJSONArray("result");
			String request_id=jsonArray==null||jsonArray.size()<=0?"":((JSONObject)jsonArray.get(0)).getString("request_id");
			return request_id;
		} catch (Exception e) {
			log.error("",e);
		}
		return "";
	}
	
	/**
	 * 获取表格识别结果
	 * @param env
	 * @param reqid:请求ID
	 * @return
	 */
	public JSONObject getTableRecognitionJsonResult(CollectInfoProperties env,String reqid) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.getTableRecognitionJsonResult(reqid);
			//countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 表格识别结果
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public JSONObject getTableRecognitionJsonResult(String app_id,String api_key,String secret_key,String reqid) {
		try {
			AipOcr aipOcr=getApiOcr(app_id,api_key,secret_key);
			org.json.JSONObject jsonObject=aipOcr.getTableRecognitionJsonResult(reqid);
			//countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 获取表格识别结果
	 * @param env
	 * @param reqid:请求ID
	 * @return
	 */
	public JSONObject getTableRecognitionExcelResult(CollectInfoProperties env,String reqid) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.getTableRecognitionExcelResult(reqid);
			//countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 表格识别结果
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public JSONObject getTableRecognitionExcelResult(String app_id,String api_key,String secret_key,String reqid) {
		try {
			AipOcr aipOcr=getApiOcr(app_id,api_key,secret_key);
			org.json.JSONObject jsonObject=aipOcr.getTableRecognitionExcelResult(reqid);
			//countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 获取表格识别
	 * @param env
	 * @param reqid:请求ID
	 * @return
	 */
	public JSONObject tableRecognizeToJson(CollectInfoProperties env,String reqid,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.tableRecognizeToJson(reqid,2000);
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 表格识别
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public JSONObject tableRecognizeToJson(String app_id,String api_key,String secret_key,String reqid,String cyrzToken,String countApiUrl) {
		try {
			AipOcr aipOcr=getApiOcr(app_id,api_key,secret_key);
			org.json.JSONObject jsonObject=aipOcr.tableRecognizeToJson(reqid,20000);
			countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 获取表格识别
	 * @param env
	 * @param reqid:请求ID
	 * @return
	 */
	public JSONObject tableRecognizeToExcelUrl(CollectInfoProperties env,String reqid,String cyrzToken) {
		try {
			AipOcr aipOcr=getApiOcr(env);
			org.json.JSONObject jsonObject=aipOcr.tableRecognizeToExcelUrl(reqid,20000);
			countBaiduApi(cyrzToken, env);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 表格识别
	 * @param env:配置文件对象
	 * @param bytes:图片二进制数组
	 * @param cyrzToken:统计token
	 * @return JSONObject(ali)
	 */
	public JSONObject tableRecognizeToExcelUrl(String app_id,String api_key,String secret_key,String reqid,String cyrzToken,String countApiUrl) {
		try {
			AipOcr aipOcr=getApiOcr(app_id,api_key,secret_key);
			org.json.JSONObject jsonObject=aipOcr.tableRecognizeToExcelUrl(reqid,20000);
			countBaiduApi(cyrzToken, countApiUrl);
			JSONObject resultJson=JSON.parseObject(jsonObject.toString());
			return resultJson;
		} catch (Exception e) {
			log.error("",e);
		}
		return new JSONObject();
	}
	
	/**
	 * 用于main方法测试 递归调用,识别图片,并将结果写入同目录文件已同名称命名的txt文本
	 * @param app_id
	 * @param api_key
	 * @param secret_key
	 * @param dir:识别目录
	 * @return
	 */
	public void whileOcr(String app_id,String api_key,String secret_key,String dir) {
		try {
			File file=new File(dir);
			File[] files=file.listFiles();
			if(files==null) {
				String name=file.getName();
				name=name.substring(0, name.indexOf("."));


				JSONObject resultJson=tableRecognizeToJson(app_id, api_key, secret_key, file.getPath(),"","");
				FileUtil.writeStrToFile(file.getParent()+"/"+name+".txt", resultJson.toJSONString());
			}else {
				for (File file2 : files) {
					if(file2.isDirectory()) {
						whileOcr(app_id, api_key, secret_key, file2.getPath());
					}else if(!file2.isDirectory()&&file2.getName().indexOf("jpg")>=0) {
						String name=file2.getName();
						name=name.substring(0, name.indexOf("."));
						JSONObject resultJson=tableRecognizeToJson(app_id, api_key, secret_key, file2.getPath(),"","");
						FileUtil.writeStrToFile(file2.getParent()+"/"+name+".txt", resultJson.toJSONString());
					}
				}
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	public static void main(String[] args) {
		String reqid="10179942_92705";
		//JSONObject result=BaiduApiUtil.INSTANCE.tableRecognitionAsync("10179942", "r6P9tH9cde3OjFa4NiQAalMF", "FWdOThT8fgG1y4bGsGKZKnLGy9j6I3mz", "D:/abc/cj/1.jpg", "", "");
		//JSONObject result=BaiduApiUtil.INSTANCE.getTableRecognitionJsonResult("10179942", "r6P9tH9cde3OjFa4NiQAalMF", "FWdOThT8fgG1y4bGsGKZKnLGy9j6I3mz", reqid);
		//FileUtil.writeStrToFile("D:/2.txt", result.toJSONString());
		//File file=new File("D:/abc/cj/1.jpg");
		//System.out.println(file.getParent());
		//BaiduApiUtil.INSTANCE.whileOcr("10179942", "r6P9tH9cde3OjFa4NiQAalMF", "FWdOThT8fgG1y4bGsGKZKnLGy9j6I3mz", "D:/D");
		
		BaiduApiUtil.INSTANCE.whileOcr("10179953", "6WuvPn12Fitf9PApTkjXkciL", "tvhyAD6VLYDQGnTiBYKdtEGKj63FiCFI", "D:/D");
	}
	
}
